<template>
  <div>
    <el-dialog
      title="导入"
      :append-to-body="true" :visible.sync="vesivleOpen" @close="close"
    >
      <el-button
        :plain="true" size="small" type="info"
        @click="downloadTemplate"
      >
        下载模板
      </el-button>
      <!-- <el-button
        :plain="true" size="small" type="danger"
        @click="exportErrorData"
      >
        导出错误数据
      </el-button> -->
      <el-upload
        ref="upload" class="upload-demo" :drag="true"
        :action="getInsertExcelUrl" :multiple="false"
        :data="importParam"
        :with-credentials="true" :file-list="listFileList"
        :headers="headerObj"
        :on-success="listHandleUploadSuccess" :on-error="handleUploadError" :on-progress="handleUploadPropress"
        :before-upload="beforeVerifyUpload" accept=".xls,.xlsx,.xlsm"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          只能上传xls/xlsx/xlsm文件
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from 'bontal-base-ui/src/store/cache-util';
import { post, postFile } from 'utils/https';
import { getOper, getGender, getBirthday, isNull } from '@/modules/index/src/common/tools';
export default {
  name: 'ImportExel',
  props: {
    importType: {
      type: String,
      default: () => ''
    },
    importExelDialogShow: {
      type: Boolean,
      default: () => false
    },
		path: {
			type: String,
      default: () => ''
		},
		// 1 是销售机构管理 2 是资格证管理 3 是人员信息录入 5 是加扣款维护
		templateId: {
			type: String,
      default: () => ''
		},
  },
  data() {
    return {
      headerObj: {
        Authorization: getToken()
      },
      listFileList: [],
			vesivleOpen: false,
			importParam: {
        code: getOper().c_login_dept_code,
      },
    };
  },
  computed: {
    getInsertExcelUrl() {
      // 返回导入的接口地址
      return '/api' + PERFORM_URL + this.path;
    }
  },
  watch: {
    importExelDialogShow: {
      handler(newval, oldval) {
        this.vesivleOpen = newval;
      },
      deep: true,
      immediate: true
    }
  },
	mounted() {
		// console.log(isNull({}));
	},
  methods: {
    // 下载模板
    downloadTemplate() {
			let fileName = '模板';
			if (this.templateId === '1') {
				fileName = '销售机构导入模板';
			} else if (this.templateId === '2') {
				fileName = '资格证导入模板';
			} else if (this.templateId === '3') {
				fileName = '人员信息录入导入模板';
			} else if (this.templateId === '4') {
				fileName = '黑名单导入模板';
			} else if (this.templateId === '6') {
				fileName = '加扣款维护导入模板';
			} else if (this.templateId === '7') {
				fileName = '税金导入';
			} else if (this.templateId === '9') {
				fileName = '考勤管理导入模板';
			} else if (this.templateId === '10') {
				fileName = '基本法点导入模板';
			} else if (this.templateId === '11') {
				fileName = '营销专项培训配置导入模板';
			} else if (this.templateId === '8') {
				fileName = '考核结果调整';
			}
      const options = {
        url: PERFORM_URL + '/file/template/' + this.templateId,
        model: {},
        fileName: fileName,
        fileType: 'xlsx'
      };
      const url = options.url;
      const data = options.model;
      post(url, data, resp => {
        // const blob = new Blob([resp], {
        //   type: 'application/vnd.ms-excel;charset=UTF-8'
        // });
        // const fileName = (options.fileName ? options.fileName : '下载文件') + '.' + options.fileType;
        // if (window.navigator.msSaveBlob) {
        //   // 兼容IE浏览器
        //   window.navigator.msSaveBlob(blob, fileName);
        // } else {
        //   const url = window.URL.createObjectURL(blob);
          // const link = document.createElement('a');
					console.log('下载模板', resp);
					window.location.href = resp.data;
					// window.open(resp.data);
          // link.href = resp.data;
          // link.href = resp.data;
          // link.setAttribute('download', fileName);
          // document.body.appendChild(link);
          // link.click();
          // document.body.removeChild(link); // 下载完成移除元素
          // window.URL.revokeObjectURL(url); // 释放掉blob对象
        // }
      }, err => {
        const message = err.message;
        err.message = message || '请求失败，请稍后重试!';
        Message.error({ message: err.message, duration: 2000 });
      });
    },
    // 错误信息导出
    exportErrorData() {
      const options = {
        url: AGENT_URL + '/pers_agency/export_error_data',
        model: {
          dataList: this.failData
        },
        fileName: '年审导入错误数据',
        fileType: 'xlsx'
      };
      const url = options.url;
      const data = options.model;
      postFile(url, data, resp => {
        const blob = new Blob([resp], {
          type: 'application/vnd.ms-excel;charset=UTF-8'
        });
        const fileName = (options.fileName ? options.fileName : '下载文件') + '.' + options.fileType;
        if (window.navigator.msSaveBlob) {
          // 兼容IE浏览器
          window.navigator.msSaveBlob(blob, fileName);
        } else {
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(url); // 释放掉blob对象
        }
      }, err => {
        const message = err.message;
        err.message = message || '请求失败，请稍后重试!';
        Message.error({ message: err.message, duration: 2000 });
      });
    },
    // 文件上传前校验
    beforeVerifyUpload: function(file) {
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf('.'));
      if (
        fileType === '.xls' ||
          fileType === '.xlsx' ||
          fileType === '.xlsm'
      ) {
        // 不处理
        // this.globalLoading = true
      } else {
        Message.warning('只能上传xls/xlsx/xlsm文件!');
        return false;
      }
    },
    // 文件上传时
    handleUploadPropress: function(event, file, fileList) {
    },
    // 文件上传失败
    handleUploadError(err, file, fileList) {
      let message = err.message.slice(4);
      message = JSON.parse(message);
      Message.error(message.message);
    },
    // 文件上传成功
    listHandleUploadSuccess(response, file, fileList) {
			if (response.code !== 200) {
				if (isNull(response.data)) {
					Message.error({ message: response.message, duration: 2000 });
				} else {
					Message.error({ message: response.data, duration: 30000 });
					// if (response.data.errorData && response.data.errorData.length > 0) {
					// 	Message.error({ message: response.data.errorData[0], duration: 2000 });
					// }
					// if (Object.prototype.toString.call(response.data).indexOf('Object') !== -1) {
					// 	const keys = Object.keys(response.data);
					// 	const values = Object.values(response.data);
					// 	const jsonString = keys.map((item, i) => {
					// 		return item + ':' + values[i];
					// 	});
					// 	Message.error({ message: jsonString.join(), duration: 5000 });
					// }
				}
				this.listFileList = this.listFileList.filter((item) => {
          if (item.uid !== file.uid) {
            return item;
          }
        });
			} else {
				this.isShowDialog = false;
				Message.success({ message: response.message, duration: 2000 });
				this.$emit('query');
			}
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    listHandleFileChange: function(file, fileList) {
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf('.'));
      if (
        fileType !== '.xls' ||
          fileType !== '.xlsx' ||
          fileType !== '.xlsm'
      ) {
        this.listFileList = fileList.filter((item) => {
          if (item.name.indexOf('.xls') !== -1 ||
              item.name.indexOf('.xlsx') !== -1 ||
              item.name.indexOf('.xlsm') !== -1
          ) {
            return item;
          }
        });
      }
      // this.listFileList = fileList.slice(-1);
    },
    close() {
      this.listFileList = [];
      this.$emit('importExcelClose');
    },
  }
};

</script>
